<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2019/11/12
 * Time: 11:38AM
 */
namespace App\Api\Controllers\Vbill;


use App\Api\Controllers\BaseController;
use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\MerchantWalletDetail;
use App\Models\Order;
use App\Models\Device;
use App\Models\OrderItem;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\UserRate;
use App\Models\UserWalletDetail;
use App\Models\VbillaStore;
use App\Models\VbillStore;
use App\Services\Pay\PayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class NotifyController extends BaseController
{
    //随行付 支付回调
    public function pay_notify_url(Request $request)
    {
        try {
            $data = $request->all();
              error_log(date('Y-m-d H:i:s')." 【vbill-notify】： ".json_encode([$data])."\n\n", 3, "/tmp/". 'vbill-notify'.date('Ymd').".log");

            // file_put_contents('return1.log',var_export($data,true)."\r\n",FILE_APPEND);
//            Log::info('随行付-支付回调');
//            Log::info($data);

            if (isset($data['ordNo'])) {
                $out_trade_no = $data['ordNo'];

                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                }

                //订单存在
                if ($order) {
                    //系统订单未成功
                    if ($order->pay_status == 2) {
                        $trade_no = isset($data['transactionId']) ? $data['transactionId'] : "";
                        $pay_time = date('Y-m-d H:i:s', strtotime($data['payTime']));
                        $buyer_pay_amount = $data['amt'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                        $buyer_id = isset($data['buyerId']) ? $data['buyerId'] : "";

                        $fee_amount = $order->rate * $buyer_pay_amount /100;

                        $in_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_id' => $buyer_id,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'fee_amount' => $fee_amount
                        ];
                        $this->update_day_order($in_data, $out_trade_no);
                        \App\Common\PaySuccessAction::addCoupon($out_trade_no, ['respData' => $data], 'pay');
                        if (strpos($out_trade_no, 'scan')) {

                        } else {
                            //支付成功后的动作
                            $data1 = [
                                'ways_type' => $order->ways_type,
                                'company' => $order->company,
                                'ways_type_desc' => $order->ways_type_desc,
                                'source_type' => '13000',//返佣来源
                                'source_desc' => '随行付',//返佣来源说明
                                'total_amount' => $order->total_amount,
                                'out_trade_no' => $order->out_trade_no,
                                'other_no' => $order->other_no,
                                'rate' => $order->rate,
                                'fee_amount' => $fee_amount,
                                'merchant_id' => $order->merchant_id,
                                'store_id' => $order->store_id,
                                'user_id' => $order->user_id,
                                'config_id' => $order->config_id,
                                'store_name' => $order->store_name,
                                'ways_source' => $order->ways_source,
                                'pay_time' => $pay_time,
                                'device_id' => $order->device_id,
                            ];
                            PaySuccessAction::action($data1);
                        }
                    }
                    //判断是否是有异步地址
                    if ($order->notify_url) {
                        $trade_no = isset($data['transactionId']) ? $data['transactionId'] : "";
                        $pay_time = date('Y-m-d H:i:s', time());
                        $array=array(
                            'return_code'=>'SUCCESS',
                            'return_msg'=>'返回成功',
                            'other_no'=>$order->other_no,
                            'store_id'=>$order->store_id,
                            'result_code'=>'SUCCESS',
                            'result_msg'=>'支付成功',
                            'out_trade_no'=>$order->out_trade_no,
                            'out_transaction_id'=>$trade_no,
                            'trade_no'=>$data['sxfUuid'],
                            'pay_time'=>$pay_time,
                            'ways_source'=>$order->ways_source,
                            'pay_amount'=>$order->pay_amount,
                            'total_amount'=>$order->total_amount,
                            'ways_source_desc'=>$order->ways_source_desc,
                        );
                        try {
                            $notify_url = $order->notify_url;
                            $in_data = $array;
                            $key = '88888888';
                            unset($in_data['sign']);
                            $string = $this->getSignContent($in_data) . '&key=' . $key;
                            $in_data['other_no'] = $order->other_no;
                            $in_data['sign'] = md5($string);
                            if (strpos($notify_url, '?') !== false) {
                                $notify_url = $notify_url . '&' . $this->getSignContent($in_data);
                                $return = $this->curlPost_java1(json_encode($in_data), $notify_url);
                            } else {
                                $notify_url = $notify_url . '?' . http_build_query($in_data);
                                $return = $this->curlPost_java1(json_encode($in_data), $notify_url);
                            }
                        } catch (\Exception $exception) {

                        }
                    }
                }
            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);

        } catch (\Exception $ex) {
            Log::info('随行付支付异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }
    
    public function curlPost_java1($data, $Url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $Url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        return $result;
    }

    //翼支付 支付回调
    public function wingpay_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            if ($data['payAmt']>0) {
                $out_trade_no = $data['outTradeNo'];

                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                }

                //订单存在
                if ($order) {
                    //系统订单未成功
                    if ($order->pay_status == 2) {
                        $trade_no = isset($data['tradeNo']) ? $data['tradeNo'] : "";
                        $pay_time = $data['tradeFinishedDate'];
                        $buyer_pay_amount = $order->total_amount;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                        $buyer_id = isset($data['buyerContractNo']) ? $data['buyerContractNo'] : "";

                        $fee_amount = $order->rate * $buyer_pay_amount /100;

                        $in_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_id' => $buyer_id,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'fee_amount' => $fee_amount
                        ];
                        $this->update_day_order($in_data, $out_trade_no);

                        if (strpos($out_trade_no, 'scan')) {

                        } else {
                            //支付成功后的动作
                            $data = [
                                'ways_type' => $order->ways_type,
                                'company' => $order->company,
                                'ways_type_desc' => $order->ways_type_desc,
                                'source_type' => '35001',//返佣来源
                                'source_desc' => '翼支付',//返佣来源说明
                                'total_amount' => $order->total_amount,
                                'out_trade_no' => $order->out_trade_no,
                                'other_no' => $order->other_no,
                                'rate' => $order->rate,
                                'fee_amount' => $fee_amount,
                                'merchant_id' => $order->merchant_id,
                                'store_id' => $order->store_id,
                                'user_id' => $order->user_id,
                                'config_id' => $order->config_id,
                                'store_name' => $order->store_name,
                                'ways_source' => $order->ways_source,
                                'pay_time' => $pay_time,
                                'device_id' => $order->device_id,
                            ];
                            PaySuccessAction::action($data);
                        }
                    }

                    //判断是否是有异步地址
                    if ($order->notify_url) {
                        try {
                            $notify_url = $order->notify_url;
                            $in_data = $data;
                            $key = '88888888';
                            $string = $this->getSignContent($in_data) . '&key=' . $key;
                            $in_data['sign'] = md5($string);
                            if (strpos($notify_url, '?') !== false) {
                                $notify_url = $notify_url . '&' . $this->getSignContent($in_data);
                                $return = $this->curlPost_java(json_encode($in_data), $notify_url);
                            } else {
                                $notify_url = $notify_url . '?' . $this->getSignContent($in_data);
                                $return = $this->curlPost_java(json_encode($in_data), $notify_url);
                            }
                            // return $return;
                        } catch (\Exception $exception) {

                        }
                    }
                }
            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);

        } catch (\Exception $ex) {
            Log::info('翼支付支付异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }
    
    public  function allin_Params(array $array){
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }
    
    public function tysmartposSend ($data)
    {
        $post=array(
            'accessKeyId' => 'IOT_ACCOUNT_PROD_MTIzNDU2Nzg5MA',
            'requestId'   => $data['out_trade_no'],
            'timestamp'   => time().'000',
            'deviceId'    => $data['deviceId'],
            'content'     => '顾客取消支付'.$data['total_amount'].'元'
        );
        error_log(date('Y-m-d H:i:s')." 【翼支付】： ".json_encode($post)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");
        ksort($post);
        $stringA=$this->allin_Params($post);
        $sign=base64_encode(hash_hmac('sha256', $stringA, 'cWF6c2RmcmU0NTZ5aHU3ODkwOWtmZ3J0c2ZmcjM0NDY1NDYzNDNkZ2ZnZmdmZXJlcg==',true));
        $post['sign']=$sign;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://voice.tysmartpos.com/api/bank/pushmsg');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        ));
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));

        $result = curl_exec($ch);
        curl_close($ch);
        error_log(date('Y-m-d H:i:s')." 【翼支付】： ".json_encode($result)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");
        return $result;
    }

    //翼支付 取消支付回调
    public function  wingpay_cancel_notify_url (Request $request)
    {
        try {
            $data = $request->all();
             error_log(date('Y-m-d H:i:s')." 【翼支付】： ".json_encode($data)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");
    
            if (isset($data['status']) && $data['status'] == 'CANCEL_PAY') {
                if (isset($data['merOrderNo']) && !empty($data['merOrderNo'])) {
                    $orderInfo = Order::where(['out_trade_no' => $data['merOrderNo']])->select('store_id', 'total_amount')->first();
                     error_log(date('Y-m-d H:i:s')." 【翼支付】： ".json_encode($orderInfo)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");
    
                    $device = Device::where(['device_type' => 'v_whty', 'store_id' => $orderInfo->store_id])->select('device_key')->first();
                     error_log(date('Y-m-d H:i:s')." 【翼支付】： ".json_encode($device)."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");
    
                    if ($device->device_key) {
                        $this->tysmartposSend([
                            'out_trade_no' => $data['merOrderNo'],
                            'deviceId' => $device->device_key,
                            'total_amount' => $orderInfo->total_amount,
                        ]);
                        Order::where('out_trade_no', $data['merOrderNo'])->update(array('status'=>3,'pay_status'=>3,'pay_status_desc'=>'支付失败'));
                    }
                }
            }
        } catch (\Exception $ex) {
             error_log(date('Y-m-d H:i:s')." 【翼支付】： ".json_encode($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine())."\n\n", 3, "/tmp/". 'bestpay'.date('Ymd').".log");
        }
    }

    //微信官方 服务商-充值回调
    public function wufushang_notifyurl(Request $request)
    {
        try {
            $data = $request->all();
            if (isset($data['ordNo'])) {
                $out_trade_no = $data['ordNo'];
                if($data['bizCode']=='0000'){
                    $log=DB::table('fullmoney_log')->where('orderNo', $out_trade_no)->first();
                    $store=DB::table('stores')->where('store_id', $log->store_id)->first();
                    $store_money=$store->store_money+$log->total_price;
                    if($log->status==1){
                        DB::table('fullmoney_log')->where('orderNo', $out_trade_no)->update(array('status'=>2));
                        Store::where('store_id', $log->store_id)->update(['store_money' => $store_money]);
                    }
                }
            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);

        } catch (\Exception $ex) {
            Log::info('支付异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }

    //平安 支付回调
    public function safepay_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            if (isset($data['out_order_id'])) {
                $out_trade_no = $data['out_order_id'];
                file_put_contents('pingan123.log',var_export($out_trade_no,true)."\r\n",FILE_APPEND);
                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                }

                //订单存在
                if ($order) {
                    //系统订单未成功
                    if ($order->pay_status == 2) {
                        $trade_no = isset($data['third_order_id']) ? $data['third_order_id'] : "";
                        $pay_time = $data['dctime'];
                        $buyer_pay_amount = $order->total_amount;
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                        $buyer_id = "";

                        $fee_amount = $order->rate * $buyer_pay_amount /100;

                        $in_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_id' => $buyer_id,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'fee_amount' => $fee_amount,
                            'merchant_id'=>$order->merchant_id
                        ];
                        $this->update_day_order($in_data, $out_trade_no);

                        if (strpos($out_trade_no, 'scan')) {

                        } else {
                            //支付成功后的动作
                            $data = [
                                'ways_type' => $order->ways_type,
                                'company' => $order->company,
                                'ways_type_desc' => $order->ways_type_desc,
                                'source_type' => '30011',//返佣来源
                                'source_desc' => '平安银行',//返佣来源说明
                                'total_amount' => $order->total_amount,
                                'out_trade_no' => $order->out_trade_no,
                                'other_no' => $order->other_no,
                                'rate' => $order->rate,
                                'fee_amount' => $fee_amount,
                                'merchant_id' => $order->merchant_id,
                                'store_id' => $order->store_id,
                                'user_id' => $order->user_id,
                                'config_id' => $order->config_id,
                                'store_name' => $order->store_name,
                                'ways_source' => $order->ways_source,
                                'pay_time' => $pay_time,
                                'device_id' => $order->device_id,
                            ];
                            PaySuccessAction::action($data);
                        }
                    }

                    //判断是否是有异步地址
                    if ($order->notify_url) {
                        try {
                            $notify_url = $order->notify_url;
                            $in_data = $data;
                            $key = '88888888';
                            $string = $this->getSignContent($in_data) . '&key=' . $key;
                            $in_data['sign'] = md5($string);
                            if (strpos($notify_url, '?') !== false) {
                                $notify_url = $notify_url . '&' . $this->getSignContent($in_data);
                                $return = $this->curlPost_java(json_encode($in_data), $notify_url);
                            } else {
                                $notify_url = $notify_url . '?' . $this->getSignContent($in_data);
                                $return = $this->curlPost_java(json_encode($in_data), $notify_url);
                            }
                            // return $return;
                        } catch (\Exception $exception) {

                        }
                    }
                }
            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);

        } catch (\Exception $ex) {
            Log::info('翼支付支付异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }

    //小程序充值 支付回调
    public function wingpay_notify_url1(Request $request)
    {
        try {
            $data = $request->all();
            // file_put_contents('wing2352.log',var_export($data,true)."\r\n",FILE_APPEND);
            if (isset($data['outTradeNo'])) {
                $out_trade_no = $data['outTradeNo'];
                if($data['tradeStatus']=='SUCCESS'){
                    $log=DB::table('fullmoney_log')->where('orderNo', $out_trade_no)->first();
                    $store=DB::table('stores')->where('store_id', $log->store_id)->first();
                    $store_money=$store->store_money+$log->total_price;
                    if($log->status==1){
                        DB::table('fullmoney_log')->where('orderNo', $out_trade_no)->update(array('status'=>2));
                        Store::where('store_id', $log->store_id)->update(['store_money' => $store_money]);
                    }
                    
                    DB::table('sms_log')->where([ 'store_id' => $log->store_id ])->update([ 'num' => 0 ]); // 重置已发短信次数
                }
            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);

        } catch (\Exception $ex) {
            Log::info('翼支付支付异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //随行付A 支付回调
    public function pay_notify_a_url(Request $request)
    {
        try {
            $data = $request->all();
//            Log::info('随行付A-支付回调');
//            Log::info($data);

            if (isset($data['ordNo'])) {
                $out_trade_no = $data['ordNo'];

                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                }

                //订单存在
                if ($order) {
                    //系统订单未成功
                    if ($order->pay_status == 2) {
                        $trade_no = isset($data['transactionId']) ? $data['transactionId'] : "";
                        $pay_time = date('Y-m-d H:i:s', strtotime($data['payTime']));
                        $buyer_pay_amount = $data['amt'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                        $buyer_id = $data['buyerId'];

                        $fee_amount = $order->rate * $buyer_pay_amount /100;

                        $in_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_id' => $buyer_id,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'fee_amount' => $fee_amount
                        ];

                        $this->update_day_order($in_data, $out_trade_no);

                        if (strpos($out_trade_no, 'scan')) {

                        } else {
                            //支付成功后的动作
                            $data = [
                                'ways_type' => $order->ways_type,
                                'company' => $order->company,
                                'ways_type_desc' => $order->ways_type_desc,
                                'source_type' => '19000',//返佣来源
                                'source_desc' => '随行付A',//返佣来源说明
                                'total_amount' => $order->total_amount,
                                'out_trade_no' => $order->out_trade_no,
                                'other_no' => $order->other_no,
                                'rate' => $order->rate,
                                'fee_amount' => $fee_amount,
                                'merchant_id' => $order->merchant_id,
                                'store_id' => $order->store_id,
                                'user_id' => $order->user_id,
                                'config_id' => $order->config_id,
                                'store_name' => $order->store_name,
                                'ways_source' => $order->ways_source,
                                'pay_time' => $pay_time,
                                'device_id' => $order->device_id,
                            ];
                            PaySuccessAction::action($data);
                        }
                    } else {
                        //系统订单已经成功了
                    }

                    //判断是否是有异步地址
                    if ($order->notify_url) {
                        try {
                            $notify_url = $order->notify_url;
                            $in_data = $data;
                            $key = '88888888';
                            $string = $this->getSignContent($in_data) . '&key=' . $key;
                            $in_data['sign'] = md5($string);
                            if (strpos($notify_url, '?') !== false) {
                                $notify_url = $notify_url . '&' . $this->getSignContent($in_data);
                                $return = $this->curlPost_java(json_encode($in_data), $notify_url);
                            } else {
                                $notify_url = $notify_url . '?' . $this->getSignContent($in_data);
                                $return = $this->curlPost_java(json_encode($in_data), $notify_url);
                            }
                            // return $return;
                        } catch (\Exception $exception) {

                        }
                    }
                }
            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);
        } catch (\Exception $ex) {
            Log::info('随行付A支付回调异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }

    public function vbill_pospay_notify(Request $request){
        $data = $request->all();
        //file_put_contents('shuaka.log',var_export($data,true)."\r\n",FILE_APPEND);
        if (isset($data['tranSts'])) {
            if($data['tranSts']=='S'){
            if(!empty($data['mno'])){
                $store_id= DB::table('vbill_stores')->where('mno', $data['mno'])->select('store_id')->first();
                if(!empty($store_id)){
                    $store=DB::table('stores')->where('store_id', $store_id->store_id)->first();
                }
                $created_at=date('Y-m-d H:i:s', time());
                $orders=DB::table('orders')->where('trade_no', $data['tranSeqNo'])->first();
                if(!empty($store_id) && empty($orders)){
                    $out_trade_no = 'pos' . date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
                    //`payment_method` varchar(255) DEFAULT NULL COMMENT 'credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知',
                    $drType=$data["drType"]??0;//1 借记卡2 贷记卡3 其他
                    $payment_method="unknown";
                    if($drType==1){
                        $payment_method="debit";
                    }else if($drType==2){
                        $payment_method="credit";
                    }
                    $order = [
                        'config_id' => '1234',
                        'out_trade_no' => $out_trade_no,
                        'trade_no' => $data['ordNo'],
                        'store_id' => $store->store_id,
                        'merchant_name' => '店长',
                        'user_id' => $store->user_id,
                        'merchant_id' => $store->merchant_id,
                        'store_name' => $store->store_name,
                        'ways_type' => '13004',
                        'rate' => $data['mecFeeRate'],
                        'ways_type_desc' => '刷卡支付',
                        'ways_source' => 'unionpay',
                        'ways_source_desc' => '刷卡支付',
                        'pay_method' => 'pos',
                        'company' => 'vbill',
                        'total_amount' => $data['tranAmt'],
                        'receipt_amount' => $data['tranAmt'],
                        'buyer_pay_amount' => $data['tranAmt'],
                        'pay_amount' => $data['tranAmt'],
                        'fee_amount' => $data['feeAmt'],
                        'shop_price' => $data['tranAmt'],
                        'shop_count' => 1,
                        'status' => 1,
                        'pay_status' => 1,
                        'pay_status_desc' => '支付成功',
                        'pay_time' => $created_at,
                        'created_at' => $created_at,
                        'updated_at' => $created_at,
                        "payment_method"=>$payment_method //刷卡支付的卡类型
                    ];
                    DB::table('orders')->insert($order);
                    //AMQP支付
                    PayService::payOkHandle($order);
                    return json_encode([
                        'code' => 'success',
                        'msg' => "成功",
                    ]);
                }else{
                    return json_encode([
                        'code' => 'success',
                        'msg' => "成功",
                    ]);
                }
            }else{
                return json_encode([
                    'code' => 'error',
                    'msg' => "无商户号",
                ]);
            }
        }else{
            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);
        }
        }else{
            if (isset($data['ordNo'])) {
                $out_trade_no = $data['ordNo'];

                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                }

                //订单存在
                if ($order) {
                    //系统订单未成功
                    if ($order->pay_status == 2) {
                        $trade_no = isset($data['transactionId']) ? $data['transactionId'] : "";
                        $pay_time = date('Y-m-d H:i:s', strtotime($data['payTime']));
                        $buyer_pay_amount = $data['amt'];
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                        $buyer_id = isset($data['buyerId']) ? $data['buyerId'] : "";

                        $fee_amount = $order->rate * $buyer_pay_amount /100;

                        $in_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'trade_no' => $trade_no,
                            'pay_time' => $pay_time,
                            'buyer_id' => $buyer_id,
                            'buyer_pay_amount' => $buyer_pay_amount,
                            'fee_amount' => $fee_amount
                        ];
                        $this->update_day_order($in_data, $out_trade_no);

                        if (strpos($out_trade_no, 'scan')) {

                        } else {
                            //支付成功后的动作
                            $data1 = [
                                'ways_type' => $order->ways_type,
                                'company' => $order->company,
                                'ways_type_desc' => $order->ways_type_desc,
                                'source_type' => '13000',//返佣来源
                                'source_desc' => '随行付',//返佣来源说明
                                'total_amount' => $order->total_amount,
                                'out_trade_no' => $order->out_trade_no,
                                'other_no' => $order->other_no,
                                'rate' => $order->rate,
                                'fee_amount' => $fee_amount,
                                'merchant_id' => $order->merchant_id,
                                'store_id' => $order->store_id,
                                'user_id' => $order->user_id,
                                'config_id' => $order->config_id,
                                'store_name' => $order->store_name,
                                'ways_source' => $order->ways_source,
                                'pay_time' => $pay_time,
                                'device_id' => $order->device_id,
                            ];
                            PaySuccessAction::action($data1);
                        }
                    }
                    //判断是否是有异步地址
                    if ($order->notify_url) {
                        try {
                            $notify_url = $order->notify_url;
                            $in_data = $data;
                            $key = '88888888';
                            unset($in_data['sign']);
                            $string = $this->getSignContent($in_data) . '&key=' . $key;
                            $in_data['other_no'] = $order->other_no;
                            $in_data['sign'] = md5($string);
                            if (strpos($notify_url, '?') !== false) {
                                $notify_url = $notify_url . '&' . $this->getSignContent($in_data);
                                $return = $this->curlPost_java(json_encode($in_data), $notify_url);
                            } else {
                                $notify_url = $notify_url . '?' . $this->getSignContent($in_data);
                                $return = $this->curlPost_java(json_encode($in_data), $notify_url);
                            }
                        } catch (\Exception $exception) {

                        }
                    }
                }
            }
            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);
        }
    }


    //随行付 退款回调
    public function refund_notify_url(Request $request)
    {
        try {
            $data = $request->all();
//            Log::info('随行付退款回调原始数据');
//            Log::info($data);

            if (isset($data['ordNo'])) {
                $out_trade_no = $data['ordNo'];
                $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
                $b = str_ireplace($a, "", $out_trade_no);
                $day = substr($b, 0, 8);
                $table = 'orders_' . $day;

                $out_trade_no = substr($out_trade_no, 0, strlen($out_trade_no)-4);

                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                }

                //订单存在
                if ($order && $order->pay_status == '1') {
                    if ($data['bizCode'] == "0000") {
                        $refund_amount = $data["totalOffstAmt"];
                        $update_data = [
                            'status' => 6,
                            'pay_status' => 6,
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $order->refund_amount + $refund_amount,
                            'fee_amount' => 0,
                        ];
                        if (Schema::hasTable($table)) {
                            DB::table($table)
                                ->where('out_trade_no', $out_trade_no)
                                ->update($update_data);
                        } else {
                            Order::where('out_trade_no', $out_trade_no)
                                ->update($update_data);
                        }
                        if (Schema::hasTable('order_items')) {
                            OrderItem::where('out_trade_no', $out_trade_no)->update($update_data);
                        }

                        RefundOrder::create([
                            'ways_source' => $order->ways_source,
                            'type' => $order->ways_type,
                            'refund_amount' => $refund_amount, //退款金额
                            'refund_no' => $data['ordNo'], //退款单号
                            'store_id' => $order->store_id,
                            'merchant_id' => $order->merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->other_no
                        ]);
                        //退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' => $data['ordNo'], //退款单号
                        ]);
                        //返佣去掉
                        UserWalletDetail::where('out_trade_no', $order->out_trade_no)->update([
                            'settlement' => '03',
                            'settlement_desc' => '退款订单',
                        ]);
                        MerchantWalletDetail::where('out_trade_no', $order->out_trade_no)->update([
                            'settlement' => '03',
                            'settlement_desc' => '退款订单',
                        ]);
                    }
                }
            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);
        } catch (\Exception $ex) {
            Log::info('随行付-退款回调异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    /**
     * curl post java对接  传输数据流
     * */
    public function curlPost_java($data, $Url)
    {
        $ch = curl_init($Url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//$data JSON类型字符串
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }


    //参数拼接
    public function getSignContent($params)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                // $v = $this->characet($v, $this->postCharset);
                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }
        unset ($k, $v);
        return $stringToBeSigned;
    }


    /**
     * 校验$value是否非空
     *  if not set ,return true;
     *    if is null , return true;
     **/
    protected function checkEmpty($value)
    {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;

        return false;
    }


    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = $this->fileCharset;
            if (strcasecmp($fileType, $targetCharset) != 0) {

                $data = mb_convert_encoding($data, $targetCharset);
                //              $data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }

        return $data;
    }


}